import pandas
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.dates import DateFormatter, AutoDateLocator

import warnings

from stressPrinter.Model import TDDataAna, MonDataAna, AnkeDataAna

warnings.filterwarnings('ignore')


def ana(data):
    max = 0
    for i, value in enumerate(data):
        if i > 0 and data[i] == 0:
            data[i] = data[i - 1]
            if data[i] > max:
                max = data[i]
    return max


def draw(data_list=None, data_list2=None, labels=None):
    if data_list is None:
        data_list = []
    if data_list2 is None:
        data_list2 = []
    if labels is None:
        labels = []
    # 创建一个Figure
    width = 12
    height = 8
    dpi = 100
    fig = plt.figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
    plt.rcParams['figure.figsize'] = (width, height)
    plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # 设置默认字体
    plt.rcParams["axes.unicode_minus"] = False  # 坐标轴正确显示正负号
    ax = fig.add_subplot(111)

    data_legend = []
    for idata in data_list:
        line = ax.plot(idata[0], idata[1])
        data_legend.append(line[0])

    if data_list2:
        ax2 = ax.twinx()
        for idata in data_list2:
            line = ax2.plot(idata[0], idata[1], c='purple', alpha=0.8, linestyle='--')
            data_legend.append(line[0])
        ax2.set_ylabel("摄氏度/℃")
    plt.legend(data_legend, labels, loc=9, bbox_to_anchor=(0.5, -0.2), shadow=True, fancybox=True, ncol=4)

    ax.set_title("对比分析", pad=25)
    ax.set_xlabel("时间")
    ax.set_ylabel("Mpa")

    locator = AutoDateLocator()
    date_fmt = DateFormatter("%Y-%m-%d %H:%M:%S")
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(date_fmt)
    ax.tick_params(direction='in', length=6, width=2, labelsize=8)
    ax.xaxis.set_tick_params(labelrotation=45)
    plt.tight_layout()
    plt.show()
    fig.savefig('对比分析.png')


def main():
    start_time_str = '2024-01-24 00:00:00'
    end_time_str = '2024-01-25 23:59:59'

    df = pandas.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
    TdData = TDDataAna.TDAna(r'../Data/G01_2024-01-24.txt')
    # TdData1 = TDDataAna.TDAna(r'../Data/G01_2024-01-25.txt')
    # TdData2 = TDDataAna.TDAna(r'../Data/G02_2024-01-24.txt')
    # TdData3 = TDDataAna.TDAna(r'../Data/G02_2024-01-25.txt')
    # TdData3 = TDDataAna.TDAna(r'../Data/G02_2024-01-25.txt')
    monData = MonDataAna.MonAna(r'D:\LK\TMV煤矿项目\应力数据分析\monidata\1\G01/G01_2024-01-24.txt')
    # AkData = AnkeDataAna.AnkeAna(r'../Data/钻孔应力传感器-10-_20240125143622.xlsx')
    df = pd.merge(df, TdData.df, how='outer')
    # df = pd.merge(df, AkData.df, how='outer')
    df = pd.merge(df, monData.df, how='outer')
    df.sort_values('time', ascending=True, inplace=True)

    chns = ['G01-1', 'G01-2', '51-1', '51-2']
    labels = ['G01-1', 'G01-2', '51-1', '51-2']
    data_list = []
    data_list2 = []

    # 绘制波形==========================================================
    for item in chns:
        sID, chnNum = item.split('-')
        df_sel = df[(start_time_str <= df['time']) & (df['time'] <= end_time_str) & (df['sID'] == sID)]
        df_sel.reset_index(drop=True, inplace=True)
        x = df_sel['time'].to_list()
        y = df_sel[f'ch{chnNum}'].to_list()
        ana(y)
        data_list.append((x, y))
    # draw(data_list, labels=labels)

    # 温度曲线==========================================================
    if 'temp' in df.columns:
        for item in chns:
            sID, chnNum = item.split('-')
            df_sel = df[
                (start_time_str <= df['time']) & (df['time'] <= end_time_str) & (df['sID'] == sID) & (df['temp'])]
            if df_sel.empty:
                continue
            df_sel.reset_index(drop=True, inplace=True)
            x = df_sel['time'].to_list()
            y = df_sel['temp'].to_list()
            data_list2.append((x, y))
            labels.append('G01-1-温度')
        draw(data_list, data_list2, labels=labels)

    # 绘制最大值波形==========================================================
    # if 'date' not in df.columns:
    #     df['date'] = df['time'].apply(lambda x: x[:10])
    # for item in sIDs:
    #     sID, chnNum = item.split('-')
    #     df_sel = df[(start_time_str <= df['time']) & (df['time'] <= end_time_str) & (df['sID'] == sID)]
    #     # df_sel['time'] = df_sel['time'].apply(lambda x: DateTimeUtil.formatDateTimeBy(time.localtime(x), "%Y-%m-%d %H:%M:%S"))
    #     df_sel['time'] = df_sel['time'].astype('datetime64[ns]')
    #     df_sel.reset_index(drop=True, inplace=True)
    #     x = df_sel['time'].to_list()
    #     y = df_sel[f'ch{chnNum}'].to_list()
    #     ana(y)
    #     df_sel = df[(start_time_str <= df['time']) & (df['time'] <= end_time_str) & (
    #             df['sID'] == sID)]
    #     x = []
    #     y = []
    #     for idate, dfi in df_sel.groupby('date'):
    #         x.append(idate)
    #         y.append(dfi[f'ch{chnNum}'].max())
    #     data_list.append((x, y))
    # draw(data_list, sIDs, dateformat=False)


if __name__ == '__main__':
    main()
